package com.fancon.android.gardenjokesx.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.fancon.android.core.IFanconGlobalState;
import com.fancon.android.emoji.widget.RichTextView;
import com.fancon.android.gardenjokesx.GardenJokesBaseActivity;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.rpc.JsonPaser;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.StringUtil;
import com.fancon.android.gardenjokesx.utils.UserUtil;
import com.fancon.android.multithread.RequestUI;
import com.fancon.android.ui.widget.FanconProgressBar;
import com.fancon.android.ui.widget.ImageCacheView;

public class FollowxActivity extends GardenJokesBaseActivity {
	private int index = 1;
	private View footerView;
	private ListView commentList;
	private Boolean isFirst = true;
	private boolean loadingMore = false;
	private ArrayList<User> listUsers = new ArrayList<User>();
	private Boolean isEnd = false;
	private UserAdapter adapter = null;
	private String mViewedUserId;
	private String mPhotoId;
	private String mUserId;
	public static final int FOLLOW = 0;
	public static final int FOLLOWING = 1;
	public static final int LIKE = 2;
	private String isFollowing;
	private TextView title;
	private int screenId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.followx_layout);

		LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View backBtn = findViewById(R.id.action_bar_button_back);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

		mUserId = UserUtil.getInfoUserLogin(this).getUser_id();
		mViewedUserId = mUserId;
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			screenId = extras.getInt(Constant.SCREEN_ID);
			mPhotoId = extras.getString(Constant.PHOTO_ID);
			if (screenId == Constant.M04) {
				mViewedUserId = extras.getString(Constant.USER_ID_VIEW);
				isFollowing = extras.getString("is_following");
			}
		}
		title = (TextView) findViewById(R.id.action_bar_textview_title);
		// Instead of screen ID
		if (screenId == Constant.M03_1) {
			title.setText(getString(R.string.gj_users));
		} else if (screenId == Constant.M04) {
			if (isFollowing != null && isFollowing.equals("true")) {
				title.setText(getString(R.string.gj_following));
			} else {
				title.setText(getString(R.string.gj_followers));
			}
		}
		footerView = layoutInflater.inflate(R.layout.listfooter, null, false);

		commentList = (ListView) findViewById(R.id.lst_id);
		commentList.setCacheColorHint(0);
		commentList.addFooterView(footerView);

		commentList.setOnScrollListener(new OnScrollListener() {

			// useless here, skip!
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
			}

			// dumdumdum
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {

				// what is the bottom iten that is visible
				int lastInScreen = firstVisibleItem + visibleItemCount;

				// is the bottom item visible & not loading more already ? Load
				// more !
				if ((lastInScreen == totalItemCount) && !(loadingMore)
						&& (!isEnd) && (!isFirst)) {
					loadMore();
				}
			}
		});
		load();
	}

	public void loadMore() {
		// footerView.setVisibility(View.VISIBLE);
		index++;
		load();
	}

	public void load() {
		GetListFollowxRequest photoReq = new GetListFollowxRequest("photo_rq", this);
		getGlobalState().getRequestQueue().addRequest(photoReq);
	}

	private void loadDataView() {
		if (adapter == null) {
			adapter = new UserAdapter(this, listUsers);
			commentList.setAdapter(adapter);
		} else {
			adapter.notifyDataSetChanged();
		}
	}

	class GetListFollowxRequest extends RequestUI {
		private Activity context;
		private FanconProgressBar progress;
		private ArrayList<User> tmp;

		public GetListFollowxRequest(Object key, Activity activity) {
			super(key, activity);
			// TODO Auto-generated constructor stub
			loadingMore = true;
			context = activity;
			if (isFirst) {
				progress = FanconProgressBar.show(context,
						context.getString(R.string.loading));
			}
		}

		@Override
		public void execute() throws Exception {
			String mAPI = null;
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
			nameValuePairs.add(new BasicNameValuePair("user_id", mUserId));
			if (screenId == Constant.M03_1) {
				mAPI = "getListUserRatingPhoto";
				nameValuePairs
						.add(new BasicNameValuePair("photo_id", mPhotoId));
			} else if (screenId == Constant.M04) {
				if (isFollowing != null && isFollowing.equals("true")) {
					mAPI = "getListUserFollow";
					nameValuePairs.add(new BasicNameValuePair("viewed_user_id",
							mViewedUserId));
					nameValuePairs.add(new BasicNameValuePair("is_following",
							"true"));
				} else {
					mAPI = "getListUserFollow";
					nameValuePairs.add(new BasicNameValuePair("viewed_user_id",
							mViewedUserId));
					nameValuePairs.add(new BasicNameValuePair("is_following",
							"false"));
				}
			}

			nameValuePairs
					.add(new BasicNameValuePair("page_index", index + ""));
			String result = "";
			try {
				GardenJokesApiConnect api = new GardenJokesApiConnect(context);
				result = api.execGet(getApplicationContext(),
						GardenJokesApiConnect.GROUP_M, mAPI, nameValuePairs);
				Log.v("StringResult", result);
			} catch (Exception e) {
				// TODO: handle exception
				Log.d("Err", e.toString());
			}
			JsonPaser js = new JsonPaser();
			tmp = js.getListUser(result);

		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			footerView.setVisibility(View.GONE);

			if (progress != null) {
				progress.dismiss();
			}
			try {
				if (tmp.size() > 0) {
					if (listUsers.size() > 0 && !isFirst) {
						listUsers.addAll(tmp);
					} else {
						listUsers = tmp;
					}
				}
				if (tmp.size() == 0) {
					isEnd = true;
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				isEnd = true;
			}
			loadDataView();
			loadingMore = false;
			isFirst = false;
		}

	}

	class UserAdapter extends BaseAdapter implements Filterable {
		private LayoutInflater mInflater;
		private Context mContext;
		private ArrayList<User> lisUser;

		public UserAdapter(Context context, ArrayList<User> lisUsers) {
			mInflater = LayoutInflater.from(context);
			this.mContext = context;
			this.lisUser = lisUsers;
		}

		public ArrayList<User> getLisPhoto() {
			return lisUser;
		}

		public void setLisPhoto(ArrayList<User> lisPhoto) {
			this.lisUser = lisPhoto;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			int ret = lisUser.size();
			return ret;
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int arg0, View convertView, ViewGroup arg2) {
			// TODO Auto-generated method stub
			final User user = lisUser.get(arg0);
			final ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.row_user, null);
				holder = new ViewHolder();
				holder.avatar = (ImageCacheView) convertView
						.findViewById(R.id.row_user_imageview);
				holder.fullName = (RichTextView) convertView
						.findViewById(R.id.row_user_fullname);
				holder.userName = (TextView) convertView
						.findViewById(R.id.row_user_username);
				holder.followBtn = (Button) convertView
						.findViewById(R.id.row_user_follow_button);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			try {
				holder.avatar.loadImage(StringUtil.processImageLink(user
						.getUrl_image()));
				holder.fullName.setText(StringUtil.getDisplayName(user));
				holder.userName.setText(user.getUser_name());
				//
				if (user.isIs_following()) {
					holder.followBtn.setText(mContext
							.getString(R.string.common_btn_following));
					holder.followBtn
							.setBackgroundResource(R.drawable.common_btn_follow_active);
				} else {
					holder.followBtn.setText(mContext
							.getString(R.string.common_btn_follow));
					holder.followBtn
							.setBackgroundResource(R.drawable.common_btn_follow);
				}
				final Boolean isAccess = (!user.isIs_private());
				// bind event
				holder.avatar.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						// if (isAccess) {
						Intent intent = new Intent();
						intent.setClass(mContext, ProfileActivity.class);
						String viewedUserId = user.getUser_id();
						intent.putExtra(Constant.USER_ID_VIEW, viewedUserId);
						mContext.startActivity(intent);
						// } else {
						// privateAlert();
						// }
					}
				});
				holder.followBtn.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (isAccess) {
							FollowRequest followReq;
							if (!user.isIs_following()) {
								holder.followBtn.setText(mContext
										.getString(R.string.common_btn_following));
								holder.followBtn
										.setBackgroundResource(R.drawable.common_btn_follow_active);
								followReq = new FollowRequest("m04gx",
										(Activity) mContext, "true",
										holder.followBtn, user);
							} else {
								holder.followBtn.setText(mContext
										.getString(R.string.common_btn_follow));
								holder.followBtn
										.setBackgroundResource(R.drawable.common_btn_follow);
								followReq = new FollowRequest("m04gx",
										(Activity) mContext, "false",
										holder.followBtn, user);
							}
							((IFanconGlobalState) mContext).getRequestQueue()
									.addRequest(followReq);
						} else {
							privateAlert();
						}

					}
				});
				holder.userName.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// if (isAccess) {
						Intent intent = new Intent();
						intent.setClass(mContext, ProfileActivity.class);
						String viewedUserId = user.getUser_id();
						intent.putExtra(Constant.USER_ID_VIEW, viewedUserId);
						mContext.startActivity(intent);
						// }else{
						// privateAlert();
						// }
					}
				});
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			return convertView;
		}

		/**
		 * Access restricted when user is private pop up show
		 */
		private void privateAlert() {
			AlertDialog alertDialog;
			AlertDialog.Builder builder = null;

			builder = new AlertDialog.Builder(mContext);
			builder.setTitle("");
			builder.setMessage(mContext.getString(R.string.m04_private_click));
			builder.setPositiveButton(
					mContext.getString(R.string.common_close),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int arg1) {
							dialog.dismiss();
						}
					});

			builder.setCancelable(false);
			alertDialog = builder.create();
			alertDialog.show();
		}

		@Override
		public Filter getFilter() {
			// TODO Auto-generated method stub
			return null;
		}

		class ViewHolder {
			ImageCacheView avatar;
			RichTextView fullName;
			TextView userName;
			Button followBtn;
		}

		class FollowRequest extends RequestUI {
			private Activity context;
			private String isFollowing;
			private String json;
			private Button follow;
			private User user;

			public FollowRequest(Object key, Activity activity,
					String isFollowing, Button follow, User user) {
				super(key, activity);
				// TODO Auto-generated constructor stub
				context = activity;
				this.isFollowing = isFollowing;
				this.follow = follow;
				this.user = user;
			}

			@Override
			public void execute() throws Exception {
				// TODO Auto-generated method stub
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				nameValuePairs.add(new BasicNameValuePair("user_id", mUserId));
				nameValuePairs.add(new BasicNameValuePair("following_user_id",
						user.getUser_id()));
				nameValuePairs.add(new BasicNameValuePair("is_following",
						isFollowing));
				GardenJokesApiConnect api = new GardenJokesApiConnect(context);
				json = api.execPost(context, GardenJokesApiConnect.GROUP_S,
						"registerFollowingUser", nameValuePairs);
				Log.v("StringResult", json);
			}

			@Override
			public void executeUI(Exception ex) {
				// TODO Auto-generated method stub
				Boolean ok = false;
				JSONObject result = new JSONObject();
				try {
					result = new JSONObject(json);
					if (result.opt("is_success") != null) {
						ok = result.getBoolean("is_success");
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (ok) {
					// change current status
					user.setIs_following(!user.isIs_following());
				} else {
					// reset text status
					//
					if (user.isIs_following()) {
						follow.setText(mContext
								.getString(R.string.common_btn_following));
						follow.setBackgroundResource(R.drawable.common_btn_follow_active);
					} else {
						follow.setText(mContext
								.getString(R.string.common_btn_follow));
						follow.setBackgroundResource(R.drawable.common_btn_follow);
					}
					try {
						Toast.makeText(context, result.getString("message"),
								1000).show();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}

		}
	}

}
